import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/21 15:49
 * @description DFS过程中添加判断，优化
 */
public class Solution2 {
    public static void main(String[] args) {

    }

    private int m;
    private int n;
    private int[][] grid1;
    private int[][] grid2;
    private int value;

    public int countSubIslands(int[][] grid1, int[][] grid2) {
        m = grid1.length;
        n = grid1[0].length;
        this.grid1 = grid1;
        this.grid2 = grid2;

        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j] == 1) {
                    value = 1;
                    dfs(i, j);
                    count += value;
                }
            }
        }
        return count;
    }
    public void dfs(int i, int j) {
        if (grid1[i][j] == 0) {
            value = 0;
        }
        // 访问过的点置为0
        grid2[i][j] = 0;
        // 与该点相邻的点，并且也是陆地，那么需要递归进去
        if (i > 0 && grid2[i-1][j] == 1) {
            dfs(i - 1, j);
        }
        if (j > 0 && grid2[i][j-1] == 1) {
            dfs(i, j - 1);
        }
        if ( i + 1 < m && grid2[i+1][j] == 1) {
            dfs(i + 1, j);
        }
        if (j + 1 < n && grid2[i][j+1] == 1) {
            dfs(i, j+1);
        }
    }
}
